package com.shujia.flink

import java.text.SimpleDateFormat

import org.apache.flink.streaming.api.TimeCharacteristic
import org.apache.flink.streaming.api.scala.StreamExecutionEnvironment
import org.apache.flink.streaming.api.windowing.time.Time
import org.apache.flink.streaming.api.windowing.windows.TimeWindow
import org.apache.flink.api.scala._
import org.apache.flink.streaming.api.functions.AssignerWithPeriodicWatermarks
import org.apache.flink.streaming.api.scala.function.WindowFunction
import org.apache.flink.streaming.api.watermark.Watermark
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows
import org.apache.flink.util.Collector

object DemoEventTIme {


  /**
    * 时间类型
    * 事件事件   数据自带的事件
    * 接收事件
    * 处理事件（默认值）
    *
    * @param args
    */
  def main(args: Array[String]): Unit = {
    val env = StreamExecutionEnvironment.getExecutionEnvironment

    //并行度
    env.setParallelism(1)

    //设置实时处理程序事件类型
    env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime)


    //通过socket创建dataStream
    val ds = env.socketTextStream("node1", 8888)


    /**
      * 1,1564108046000
      * 1,1564108051000
      * 1,1564108054000
      * 2,1564108046000
      *
      *
      */

    val eventDS = ds.map(line => {
      val split = line.split(",")
      println(split.mkString(","))
      (split(0), split(1).toLong)
    })

    eventDS
      .assignAscendingTimestamps(_._2) //指定哪一个字段为事件时间
      .map(t => (t._1, 1))
      .keyBy(0)
      .timeWindow(Time.seconds(5))//基于事件时间的窗口
      .reduce((x, y) => (x._1, x._2 + y._2))
      .print()


    env.execute()

  }

}